﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;

using BusinessFacade;
using EntityManage;


public partial class Modules_Personal_EvaluateAdd : System.Web.UI.Page
{
    IPerf_Personal_EvaluateHandler evaluateHandler = new Perf_Personal_EvaluateManage();
    IPerf_Personal_EvaluateDtlHandler evaluateDtlHandler = new Perf_Personal_EvaluateDtlManage();

    ISys_OrganizationHandler organizationHandler = new Sys_OrganizationManage();

    IPerf_Personal_TargetOwnerHandler targetOwnerHandler = new Perf_Personal_TargetOwnerManage();
    DataBase db = new DataBase();

    ISys_UserHandlerExt userHandlerExt = new Sys_UserManageExt();
    IPerf_Personal_EvaluateHandlerExt evaluateHandlerExt = new Perf_Personal_EvaluateManageExt();
    IPerf_Personal_FinalAssignHandler finalAssignHandler = new Perf_Personal_FinalAssignManage();
    static string finalAssignID = string.Empty;
    static string s_targetID = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (!CheckPurviews())
        //{
        //    Response.Redirect("~/Login.aspx");
        //}
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Id";
            ViewState["Accending"] = "desc";
            dataBind();

        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            //if (strPur.Contains("303000"))
            //{

            //}
            //else
            //{
            //    return false;
            //}
            return true;
        }
        else
        {
            return false;
        }
    }

    public string GetUserName(object id)
    {
        return userHandlerExt.GetUserNameByID(int.Parse(id.ToString()));
    }

    public string GetTargetOwner(object id)
    {
        string name = string.Empty;
        Perf_Personal_TargetOwnerQuery query = targetOwnerHandler.GetPerf_Personal_TargetOwnerQuery(int.Parse(id.ToString()));
        if (query != null)
        {
            name = query.Name;
        }
        return name;
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();


        if (ViewState["Name"] != null)
        {
            whereClause += " and u.Name  like + '%' + @Name + '%'";
            lstParm.Add(new SqlParameter("@TargetOwner_ID", ViewState["TargetOwner_ID"].ToString()));
        }

        parms = lstParm.ToArray();
    }

    private void dataBind()
    {
        //当前用户所属部门(如果当前用户有借调部门就优先借调部门)
        int currUserOrgID = 0;
        if (Session["OrgID2"] != null)
        {
            if (Session["OrgID2"].ToString() != string.Empty && Session["OrgID2"].ToString() != "0")
            {
                currUserOrgID = int.Parse(Session["OrgID2"].ToString());
            }
            else if (Session["OrgID"] != null)
            {
                currUserOrgID = int.Parse(Session["OrgID"].ToString());
            }
        }

        Sys_OrganizationQuery orgQuery = organizationHandler.GetSys_OrganizationQuery(currUserOrgID);
        if (orgQuery != null)
        {

            //获取父部门
            Sys_OrganizationQuery orgPQuery = organizationHandler.GetSys_OrganizationQuery(orgQuery.Parent_ID);

            if (orgPQuery != null)
            {
                //根据父部门ID获取所有子部门ID
                string subOrgID = string.Empty;
                string sqlSub = @"select ID from Sys_Organization where Parent_ID=" + orgPQuery.ID;
                DataTable dtSub = db.RunSql(sqlSub);
                if (dtSub != null && dtSub.Rows.Count > 0)
                {
                    foreach (DataRow r in dtSub.Rows)
                    {
                        subOrgID += r["ID"].ToString() + ",";
                    }

                    //当前用户是属于工商所或机关才有评分
                    if (orgQuery.Type.ToString() == Enums.OrgType.Office.ToString("d") || (orgQuery.Type.ToString() == Enums.OrgType.ICU.ToString("d"))
                        || orgPQuery.Type.ToString() == Enums.OrgType.Office.ToString("d") || (orgPQuery.Type.ToString() == Enums.OrgType.ICU.ToString("d")))
                    {
                        string sqlStr = @"
                select pf.ID, u.Name,pf.Target_User_ID,pf.TargetOwner_ID,tarO.Name,(case when u.Org_ID2>0 then Org_ID2 else u.Org_ID end) as ORGID  from                Perf_Personal_FinalAssign pf inner join Sys_User u                 on pf.Target_User_ID=u.ID                 inner join Perf_Personal_TargetOwner tarO on pf.TargetOwner_ID=tarO.ID
                where (case when u.Org_ID2>0 then Org_ID2 else u.Org_ID end)in(" + subOrgID.TrimEnd(new char[] { ',' }) + ") ";

                        DataTable dtCounter = new DataTable();
                        int counter = 0;
                        DataTable dt = new DataTable();
                        SqlParameter[] parms1 = null;
                        SqlParameter[] parms2 = null;
                        string whereClause = string.Empty;
                        ProcessParms(ref whereClause, ref parms1);
                        ProcessParms(ref whereClause, ref parms2);

                        if (whereClause != string.Empty)
                        {

                            dt = db.GetDataTableByIndex(sqlStr + whereClause + " order by " + ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), parms1, AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                            whereClause = "1=1";
                            dtCounter = db.RunSqlTab(sqlStr + whereClause, parms2);
                            if (dtCounter != null && dtCounter.Rows.Count > 0)
                            {
                                counter = dtCounter.Rows.Count;
                            }
                        }
                        else
                        {
                            dt = db.GetDataTableByIndex(sqlStr + " order by " + ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);
                            dtCounter = db.RunSql(sqlStr);
                            if (dtCounter != null && dtCounter.Rows.Count > 0)
                            {
                                counter = dtCounter.Rows.Count;
                            }
                        }

                        this.AspNetPager.RecordCount = counter;
                        gvUserList.DataSource = dt;
                        gvUserList.DataBind();

                        divUser.Style.Add("display", "block");
                        divDetail.Style.Add("display", "none");
                        //   btnSave.Enabled = false;
                    }
                }
            }
        }
    }



    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtName.Text != string.Empty)
            ViewState["Name"] = txtName.Text.Trim();
        else
            ViewState["Name"] = null;

        dataBind();
    }

    protected void gvUserList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
    }

    protected void gvUserList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
    }

    protected void gvUserList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }



    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {

        dataBind();
    }


    #region Detail


    private void DetailBind()
    {
       // this.gvTarget.Attributes.Add("style", "width:100px;word-break:break-all;word-wrap:break-word;");
       // this.gvTarget.Attributes.Add("style", "width:100px;word-break:break-all;word-wrap:break-word;");
       // gvTarget.Attributes.Add("style", "word-break:keep-all;word-wrap:normal");


        if (Request["chkSelected"] != null)
        {
            finalAssignID = Request["chkSelected"];
        }
        if (finalAssignID != string.Empty)
        {
            hidFinAssID.Value = finalAssignID;

            Perf_Personal_FinalAssignQuery query = finalAssignHandler.GetPerf_Personal_FinalAssignQuery(int.Parse(finalAssignID));
            if (query != null)
            {

                txtUser.Text = GetUserName(query.Target_User_ID);
                divUser.Style.Add("display", "none");
                divDetail.Style.Add("display", "block");
                //  btnSave.Enabled = true;

                //详细指标评分
                string sqlStr = @"select FD.Target_ID,T.Name,T.Score from Perf_Personal_FinalAssignDtl FD 
inner join Perf_Personal_Target T on FD.Target_ID=T.ID inner join Sys_User u on u.Assign_ID=FD.Final_Assign_ID where Final_Assign_ID=@Final_Assign_ID ";
                DataTable dtCounter = db.RunSqlTab(sqlStr, new SqlParameter[] { new SqlParameter("@Final_Assign_ID", finalAssignID) });
                DataTable dt = db.GetDataTableByIndex(sqlStr, new SqlParameter[] { new SqlParameter("@Final_Assign_ID", finalAssignID) }, AspNetPager2.StartRecordIndex - 1, AspNetPager2.PageSize);

                if (dt != null && dt.Rows.Count > 0)
                {
                    AspNetPager2.RecordCount = dtCounter.Rows.Count;
                }
                gvTarget.DataSource = dt;
                gvTarget.DataBind();
            }
        }
    }

    

    /// <summary>
    /// 获取评分发生次数
    /// </summary>
    /// <param name="targetID"></param>
    /// <returns></returns>
    public string GetNum(object targetID)
    {
        int counter = 0;
        int evaluateID = 0;
        if (hidEvaluateID.Value != string.Empty)
        {
            int.TryParse(hidEvaluateID.Value, out evaluateID);
        }
        string sqlStr = @"select count(*) as counter from Perf_Personal_EvaluateDtl where Target_ID=@Target_ID and Evaluate_ID=@Evaluate_ID";
        DataTable dt= db.RunSqlTab(sqlStr, new SqlParameter[] { new SqlParameter("@Target_ID", targetID.ToString()), new SqlParameter("@Evaluate_ID", evaluateID.ToString()) });

        if (dt != null && dt.Rows.Count > 0)
        { 
          int.TryParse(dt.Rows[0]["counter"].ToString(),out counter);
        }
        return counter.ToString();

    }
   
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        DetailBind();
    }

    protected void gvTarget_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "input")
        {
            try
            {
                string _targetID = string.Empty;
                if (hidEvaluateID.Value == string.Empty)
                {

                    if (hidFinAssID.Value != string.Empty)
                    {
                        string finalAssignID = hidFinAssID.Value;

                        Perf_Personal_FinalAssignQuery query = finalAssignHandler.GetPerf_Personal_FinalAssignQuery(int.Parse(finalAssignID));
                        if (query != null)
                        {

                            Perf_Personal_EvaluateQuery q = new Perf_Personal_EvaluateQuery();
                            q.User_ID = int.Parse(Session["CurrentUserID"].ToString());
                            q.Target_User_ID = query.Target_User_ID;
                           
                            q.TargetOwner_ID = query.TargetOwner_ID;
                            q.Status = int.Parse(Enums.PEvaluateStatus.AddNew.ToString("d"));
                            q.Create_Time = DateTime.Now;
                            q.Final_Assign_ID = query.ID;
                            int evaluateID = 0;
                            if (evaluateHandler.InsertPerf_Personal_Evaluate(q, ref evaluateID))
                            {
                                hidEvaluateID.Value = evaluateID.ToString();

                                Perf_Personal_EvaluateDtlQuery Querys = new Perf_Personal_EvaluateDtlQuery();
                                if (gvTarget != null && gvTarget.Rows.Count > 0)
                                {

                                    foreach (GridViewRow row in gvTarget.Rows)
                                    {
                                        TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
                                        HiddenField HidTargetID = (HiddenField)row.FindControl("HidTargetID");
                                        HtmlInputText txtDate = (HtmlInputText)row.FindControl("txtDate");
                                        TextBox txtScore = (TextBox)row.FindControl("txtScore");
                                        if (HidTargetID.Value == e.CommandArgument.ToString())
                                        {
                                            Perf_Personal_EvaluateDtlQuery dtlQ = new Perf_Personal_EvaluateDtlQuery();

                                            double score = 0;
                                            double.TryParse(txtScore.Text, out score);
                                            dtlQ.Target_ID = int.Parse(HidTargetID.Value);
                                            //被考核人ID
                                            s_targetID = HidTargetID.Value;
                                            dtlQ.Score = score;
                                            dtlQ.Remark = txtRemark.Text;
                                            dtlQ.Evaluate_ID = evaluateID;
                                            dtlQ.InsertTime = DateTime.Parse(txtDate.Value);
                                            dtlQ.User_ID = int.Parse(Session["CurrentUserID"].ToString());
                                            evaluateDtlHandler.InsertPerf_Personal_EvaluateDtl(dtlQ);
                                            break;
                                        }

                                    }
                                    //判断最终分配表状态是否是新增，是就修改为已评分
                                    if (query.Status == 0)
                                    {
                                        query.Status = 1;//已评分
                                        finalAssignHandler.UpdatePerf_Personal_FinalAssign(query);
                                    }
                                }


                            }


                        }
                    }

                }
                else
                {
                    Perf_Personal_EvaluateDtlQuery Querys = new Perf_Personal_EvaluateDtlQuery();
                    if (gvTarget != null && gvTarget.Rows.Count > 0)
                    {

                        foreach (GridViewRow row in gvTarget.Rows)
                        {
                            TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
                            HiddenField HidTargetID = (HiddenField)row.FindControl("HidTargetID");
                            HtmlInputText txtDate = (HtmlInputText)row.FindControl("txtDate");
                            TextBox txtScore = (TextBox)row.FindControl("txtScore");
                            if (HidTargetID.Value == e.CommandArgument.ToString())
                            {
                                Perf_Personal_EvaluateDtlQuery dtlQ = new Perf_Personal_EvaluateDtlQuery();

                                //int iEvaluate = 0;
                                //if (!int.TryParse(txtEvaluate.Text.Trim(), out iEvaluate) || iEvaluate < 0)
                                //{
                                //    Jscript.Alert("分数不能为整数!", this);
                                //    return;
                                //}
                                double score = 0;
                                double.TryParse(txtScore.Text, out score);
                                dtlQ.Target_ID = int.Parse(HidTargetID.Value);
                                //被考核人ID
                                s_targetID = HidTargetID.Value;
                                dtlQ.Score = score;
                                dtlQ.Remark = txtRemark.Text;
                                dtlQ.Evaluate_ID = int.Parse(hidEvaluateID.Value);
                                dtlQ.InsertTime = DateTime.Parse(txtDate.Value);
                                dtlQ.User_ID = int.Parse(Session["CurrentUserID"].ToString());
                                evaluateDtlHandler.InsertPerf_Personal_EvaluateDtl(dtlQ);
                                break;
                            }

                        }
                    }

                }
                DetailBind();
                Jscript.AlertInAjax("操作成功!", UpdatePanel2);
                dataHis(s_targetID);
            }
            catch { Jscript.AlertInAjax("操作失败!", UpdatePanel2); }


        }

        else if (e.CommandName == "his")
        {
            s_targetID = e.CommandArgument.ToString();
            dataHis(s_targetID);
        }
    }

    private void dataHis(string targetID)
    {
        if (hidEvaluateID.Value == string.Empty)
        {
            Jscript.AlertInAjax("还没评分!", UpdatePanel2);
            return;
        }
        else
        {
            divHis.Style.Add("display", "block");
            gvHis.DataSource = null;

            string sqlStr = @"select t.Name,edtl.Score,edtl.Evaluate_ID, edtl.User_ID,edtl.Target_ID,edtl.InsertTime,edtl.Remark
from Perf_Personal_EvaluateDtl edtl 
inner join Perf_Personal_Target t on t.ID=edtl.Target_ID where Target_ID=@Target_ID and Evaluate_ID=@Evaluate_ID";
            DataTable dtCounter = db.RunSqlTab(sqlStr, new SqlParameter[] { new SqlParameter("@Target_ID", s_targetID), new SqlParameter("@Evaluate_ID", hidEvaluateID.Value) });

            if (dtCounter != null && dtCounter.Rows.Count > 0)
            {
                AspNetPagerHis.RecordCount = dtCounter.Rows.Count;
            }
            DataTable dt = db.GetDataTableByIndex(sqlStr, new SqlParameter[] { new SqlParameter("@Target_ID", s_targetID), new SqlParameter("@Evaluate_ID", hidEvaluateID.Value) }, AspNetPagerHis.StartRecordIndex - 1, AspNetPagerHis.PageSize);

            gvHis.DataSource = dt;
            gvHis.DataBind();
        }
    }

    protected void gvTarget_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    e.Row.Cells[0].Style.Add("word-break", "break-all");
        //}
    }

    protected void gvTarget_Sorting(object sender, GridViewSortEventArgs e)
    {

    }

    protected void AspNetPager2_PageChanged(object src, EventArgs e)
    {

        DetailBind();
    }

    protected void AspNetPagerHis_PageChanged(object src, EventArgs e)
    {
        dataHis(s_targetID);
        

    }

    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
        //try
        //{
        //    if (hidFinAssID.Value != string.Empty)
        //    {
        //        string finalAssignID = hidFinAssID.Value;

        //        Perf_Personal_FinalAssignQuery query = finalAssignHandler.GetPerf_Personal_FinalAssignQuery(int.Parse(finalAssignID));
        //        if (query != null)
        //        {

        //            Perf_Personal_EvaluateQuery q = new Perf_Personal_EvaluateQuery();
        //            q.User_ID = int.Parse(Session["CurrentUserID"].ToString());
        //            q.Target_User_ID = query.Target_User_ID;
        //            q.TargetOwner_ID = q.TargetOwner_ID;
        //            q.Status = int.Parse(Enums.PEvaluateStatus.AddNew.ToString("d"));
        //            q.Create_Time = DateTime.Now;
        //            q.Final_Assign_ID = query.ID;
        //            int evaluateID = 0;
        //            if (evaluateHandler.InsertPerf_Personal_Evaluate(q, ref evaluateID))
        //            {

        //                List<Perf_Personal_EvaluateDtlQuery> lstQuerys = new List<Perf_Personal_EvaluateDtlQuery>();
        //                if (gvTarget != null && gvTarget.Rows.Count > 0)
        //                {

        //                    foreach (GridViewRow row in gvTarget.Rows)
        //                    {
        //                        Perf_Personal_EvaluateDtlQuery dtlQ = new Perf_Personal_EvaluateDtlQuery();

        //                        TextBox txtEvaluate = (TextBox)row.FindControl("txtScore");
        //                        TextBox txtRemark = (TextBox)row.FindControl("txtRemark");
        //                        HiddenField HidTargetID = (HiddenField)row.FindControl("HidTargetID");
        //                        int iEvaluate = 0;
        //                        if (!int.TryParse(txtEvaluate.Text.Trim(), out iEvaluate) || iEvaluate < 0)
        //                        {
        //                            Jscript.Alert("分数不能为整数!", this);
        //                            return;
        //                        }

        //                        dtlQ.Target_ID = int.Parse(HidTargetID.Value);
        //                        dtlQ.Score = iEvaluate;
        //                        dtlQ.Remark = txtRemark.Text;
        //                        dtlQ.Evaluate_ID = evaluateID;
        //                        lstQuerys.Add(dtlQ);


        //                    }
        //                    evaluateDtlHandler.InsertPerf_Personal_EvaluateDtl(lstQuerys.ToArray());
        //                }

        //                //判断最终分配表状态是否是新增，是就修改为已评分
        //                if (query.Status == 0)
        //                {
        //                    query.Status = 1;//已评分
        //                    finalAssignHandler.UpdatePerf_Personal_FinalAssign(query);
        //                }
        //            }


        //        }
        //    }
        //    Jscript.Alert("操作成功!", this.Page);
        //    Jscript.ReturnAndClose(this.Page, "true");
        //}
        //catch { Jscript.Alert("操作失败!", this.Page); }

    }
}
